/*
 * Copyright 2025 The JA-SIG Collaborative. All rights reserved. distributed with this file and
 * available online at
 */
package com.lap.auth.adapter.driving.persistence.msg.repository;

import com.lap.auth.adapter.driving.persistence.msg.MsgTemplateConverter;
import com.lap.auth.adapter.driving.persistence.msg.mapper.MsgTemplateMapper;
import com.lap.auth.adapter.driving.persistence.msg.po.MsgTemplatePo;
import com.lap.auth.domain.msg.MsgTemplate;
import com.lap.auth.domain.msg.repository.MsgTemplateRepository;
import java.util.Optional;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Repository;

@RequiredArgsConstructor
@Repository
public class MsgTemplateRepositoryImpl implements MsgTemplateRepository {

  private final MsgTemplateConverter converter;
  private final MsgTemplateMapper msgTemplateMapper;

  @Override
  public Integer save(MsgTemplate msgTemplate) {
    MsgTemplatePo msgTemplatePo = converter.toPo(msgTemplate);
    if (msgTemplate.isNew()) {
      msgTemplateMapper.insert(msgTemplatePo);
      return msgTemplatePo.getId();
    }
    return msgTemplateMapper.updateById(msgTemplatePo);
  }

  @Override
  public int deleteById(Integer id) {
    return msgTemplateMapper.deleteById(id);
  }

  @Override
  public Optional<MsgTemplate> findById(Integer id) {
    var msgTemplateDO = msgTemplateMapper.selectById(id);
    return Optional.ofNullable(converter.toDomain(msgTemplateDO));
  }

  @Override
  public Optional<MsgTemplate> findByCode(String code) {
    var msgTemplateDO = msgTemplateMapper.selectByCode(code);
    return Optional.ofNullable(converter.toDomain(msgTemplateDO));
  }
}
